# _*_ coding:utf-8 _*_
# @author : Joyamon
# @time : 2022-12-16 15:09
# @file : excel.py
from io import BytesIO
import xlsxwriter


class Excel:
    def export(self, columns=[], values=None):
        """
        columns :表字段
        values:导出的数据
        """
        # 创建数据流
        output = BytesIO()
        # 创建excel work book
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet('user')
        col_format = workbook.add_format({
            'bold': 1,
            'border': 1,
            'align': 'center',
            'valign': 'vcenter',
            'fg_color': '#f4cccc'})
        # 设置标题
        worksheet.merge_range(0, 0, 0, len(values) - 1, '用户表',col_format.set_align('center'))
        # cell 样式
        col_format = workbook.add_format({
            'bold': 1,
            'border': 1,
            'align': 'center',
            'valign': 'vcenter',
            'fg_color': '#f4cccc'})
        cont_format = workbook.add_format({
            'bold': 1,
            'border': 1,
            'align': 'center',
            'valign': 'vcenter',
            'fg_color': '#f9f9fb'})


        # 写入列名
        col = 0
        for item in columns:
            worksheet.write(1, col, item, col_format)
            col += 1
        # 写入数据
        id = [value.id for value in values]
        username = [value.username for value in values]
        password = [value.password for value in values]
        phone = [value.phone for value in values]
        email = [value.email for value in values]
        icon = [value.icon for value in values]
        isdelete = [value.isdelete for value in values]
        createTime = [value.createTime for value in values]
        for i in range(len(values)):
            worksheet.write(i + 2, 0, id[i], cont_format)
            worksheet.write(i + 2, 1, username[i], cont_format)
            worksheet.write(i + 2, 2, password[i], cont_format)
            worksheet.write(i + 2, 3, phone[i], cont_format)
            worksheet.write(i + 2, 4, email[i], cont_format)
            worksheet.write(i + 2, 5, icon[i], cont_format)
            worksheet.write(i + 2, 6, isdelete[i], cont_format)
            worksheet.write(i + 2, 7, createTime[i], cont_format)
        # 设置A-E的宽
        worksheet.set_column('A:E', 20)
        workbook.close()
        output.seek(0)
        return output
